package com.ruoyi.framework.resolves;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.annotation.LoginUserInfo;
import com.ruoyi.common.constant.BuConstants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.framework.interceptor.AuthInterceptor;
import com.ruoyi.projects.Vos.WxUserInfoDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;


/**
 * 参数解析器
 * 有@LoginUser注解的方法参数，注入当前登录用户
 * @date 2017-03-23 22:02
 */
@Service
public class LoginUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    private RedisCache redisCache;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        //进行解析注入的条件有两个
        //第一个isAssignableFrom(class2) 判定此 Class 对象所表示的类或接口与指定的 Class 参数所表示的类或接口是否相同，或是否是其超类或超接口
        //第二个该接口参数有@LoginUser注解
        return parameter.getParameterType().isAssignableFrom(WxUserInfoDTO.class) && parameter.hasParameterAnnotation(LoginUserInfo.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer container,
                                  NativeWebRequest request, WebDataBinderFactory factory) throws Exception {
        //获取用户ID
        Object object = request.getAttribute(AuthInterceptor.LOGIN_USER_KEY, RequestAttributes.SCOPE_REQUEST);
        if (object == null) {
            return null;
        }
        //获取用户信息
        String token = (String) object;
        Object userInfoObject= redisCache.getCacheObject(BuConstants.MINITOKEN+token);
        WxUserInfoDTO apiUserVo = (WxUserInfoDTO)userInfoObject;
        return apiUserVo;
    }
}
